Skip to content

Conversation

SarahSoutoul
Copy link
Contributor

@SarahSoutoul SarahSoutoul commented Oct 1, 2025

Description

Fixes https://linear.app/clerk/issue/DOCS-10983/ensure-all-hooks-are-using-typedocs-have-code-examples-for-each.

This PR is part of a broader project aimed at adding more code examples to our hooks documentation. During project discussions, we agreed that the current structure of our hooks docs needed to be revisited. Currently, most of the hook pages are fully rendered through Typedoc, including code examples. However, adding additional examples through Typedoc would have required significant restructuring of the JavaScript repo.

To address this, we decided to:

  • Use Typedoc only for documenting returns and parameters. This is achieved through this PR.
  • Write SDK-specific explanations and code examples directly in the docs instead of generating them via Typedoc. PR on clerk-docs for this: https://github.com/clerk/clerk-docs/pull/2649/files

Additionally, not all hooks currently use Typedoc. This PR also ensures that all hooks are properly configured to use Typedoc for their returns and parameters.

This PR includes:

  • Adding JSDoc comments to the billing hooks so their returns and parameters are correctly pulled from Typedoc.
  • Updating the documentation setup to ensure Typedoc is used only for returns and parameters, not for examples or SDK explanations.

This PR will be the first in a sequence. Once merged, we’ll proceed with its sibling PR in clerk-docs, which:

  • Adds code examples for all supported SDKs.
  • Ensures the updated Typedoc outputs are properly integrated into the docs site.

Hooks checklist

  • Check all the returns render properly for all hooks - can be compared to what's on the live docs (if you'd like a list of all the hooks to check, you can navigate to this PR's description).
  • Check the params render properly for useAuth, useReverification and the billing hooks - can be compared to what's on the live docs.

How to test

In order to test this properly, you will need to do the following:

  • On the javascript repo, switch to the branch of this PR
  • Run pnpm run typedoc:generate
  • Navigate to the clerk-docs repo, and switch to the branch of this PR - ss/DOCS-10983
  • Run npm run typedoc:link ../javascript/.typedoc/docs
  • Now, you can run the docs locally and be able to see the returns and params on each hook, coming through Typedoc.

Important notes/ discussion pts

  • I noticed we use the terminology Parameters for some hooks and for others, we use Properties: We probably want some consistency, so want to open this for discussion.
Screenshot 2025-10-14 at 8 31 46 am Screenshot 2025-10-14 at 8 35 22 am

Checklist

  • pnpm test runs as expected.
  • pnpm build runs as expected.
  • (If applicable) JSDoc comments have been added or updated for any package exports
  • (If applicable) Documentation has been updated

Type of change

  • 🐛 Bug fix
  • 🌟 New feature
  • 🔨 Breaking change
  • 📖 Refactoring / dependency upgrade / documentation
  • other:

Summary by CodeRabbit

  • New Features

    • Expanded public types for payment element, checkout, reverification, and subscription APIs; subscription hook adds a manual revalidate action.
  • Documentation

    • Added JSDoc and expanded reference docs across payment, checkout, reverification, subscription, and billing fields; generated separate returns/parameters docs and updated internal link mappings.
  • Chores

    • Updated documentation tooling and post-processing scripts and added a changeset for versioning.

Copy link

vercel bot commented Oct 1, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
clerk-js-sandbox Ready Ready Preview Comment Oct 16, 2025 11:38pm

Copy link

changeset-bot bot commented Oct 1, 2025

🦋 Changeset detected

Latest commit: 6b4f930

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 22 packages
Name Type
@clerk/shared Minor
@clerk/types Minor
@clerk/agent-toolkit Patch
@clerk/astro Patch
@clerk/backend Patch
@clerk/chrome-extension Patch
@clerk/clerk-js Patch
@clerk/elements Patch
@clerk/expo-passkeys Patch
@clerk/clerk-expo Patch
@clerk/express Patch
@clerk/fastify Patch
@clerk/nextjs Patch
@clerk/nuxt Patch
@clerk/react-router Patch
@clerk/clerk-react Patch
@clerk/remix Patch
@clerk/tanstack-react-start Patch
@clerk/testing Patch
@clerk/vue Patch
@clerk/localizations Patch
@clerk/themes Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Copy link
Contributor

coderabbitai bot commented Oct 1, 2025

Walkthrough

Exported and documented multiple TypeScript public types across hooks and React components (payment, checkout, reverification, subscription); added Typedoc post-processing entries and a docs extraction script. Changes are primarily type/export and doc updates; no behavioral/runtime changes in the code paths shown.

Changes

Cohort / File(s) Summary
Payment element public typings
packages/shared/src/react/commerce.tsx
Exported and documented PaymentElementProviderProps, PaymentElementProps, and UsePaymentElementReturn; PaymentElement now types its props with PaymentElementProps. No runtime behavior changes.
Checkout context options
packages/shared/src/react/contexts.tsx
Made UseCheckoutOptions an exported, JSDoc-annotated type. Structure unchanged.
useCheckout API surface
packages/shared/src/react/hooks/useCheckout.ts
Added exported UseCheckoutReturn and UseCheckoutParams; replaced inline checkout type with UseCheckoutReturn and updated useCheckout signature and JSDoc. No runtime changes.
useReverification API surface
packages/shared/src/react/hooks/useReverification.ts
Exported previously internal types: NeedsReverificationParameters, UseReverificationOptions, and UseReverification (simplified generic signature). Changes are type/signature and docs only.
useSubscription public types
packages/shared/src/react/hooks/useSubscription.tsx
Added and exported UseSubscriptionParams and UseSubscriptionReturn and documented the hook return (including revalidate). No runtime logic changes shown.
Billing types docs
packages/types/src/billing.ts
Clarified JSDoc for BillingCheckoutResource.planPeriodStart as a Unix timestamp. No type/behavior changes.
Typedoc plugin config
.typedoc/custom-plugin.mjs
Removed duplicate entry, added many MDX files to FILES_WITHOUT_HEADINGS, and expanded LINK_REPLACEMENTS/billing mappings. Affects docs post-processing only.
Typedoc extraction script
.typedoc/extract-returns-and-params.mjs
Added a script that extracts "Returns" and "Parameters" sections into -return.mdx/-params.mdx, replaces a generic type pattern in params tables, and removes stale -props.mdx.
Changeset
.changeset/violet-boxes-watch.md
Added changeset noting minor package bumps and a docs guidance note.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant S as Script (extract-returns-and-params.mjs)
  participant FS as FileSystem
  participant M as MDX File
  participant P as Params/Returns Outputs

  S->>FS: enumerate MDX files under temp-docs/
  FS-->>S: list of files
  loop each file
    S->>M: read file
    M-->>S: file content
    alt contains "## Returns"
      S->>S: extract Returns section
      S->>P: write <file>-return.mdx
    end
    alt contains "## Parameters"
      S->>S: extract Parameters section
      S->>S: replace generic type pattern in table
      S->>P: write <file>-params.mdx
      S->>FS: delete existing -props.mdx (if present)
    end
  end
  S->>FS: log counts and exit
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

I hop through types with whiskers bright,
Exports lined up in tidy rows tonight,
Docs sprout paths where functions roam,
Scripts carve returns from every tome,
Merge the garden — nibble, then home. 🥕🐇

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title "docs(repo): Generate all params and return types (hooks work)" accurately reflects the primary change of the pull request. The PR exports new types for hook parameters and returns (UseCheckoutReturn, UseCheckoutParams, UseReverificationOptions, NeedsReverificationParameters, UseSubscriptionParams, UseSubscriptionReturn, and others) and adds JSDoc documentation to enable TypeDoc to capture this metadata. The additions of a TypeDoc extraction script and plugin updates further support this core objective. The title is concise, specific, and would be clear to a teammate reviewing the commit history.
Linked Issues Check ✅ Passed The PR successfully addresses the core technical requirements of DOCS-10983. It exports typed metadata for hook parameters and returns across multiple hooks (useCheckout, useReverification, useSubscription, payment element hooks) with corresponding JSDoc documentation to enable TypeDoc capture [useCheckout.ts, useReverification.ts, useSubscription.tsx, commerce.tsx, contexts.tsx]. The PR includes a new TypeDoc extraction script (.typedoc/extract-returns-and-params.mjs) that processes generated MDX files to isolate returns and parameters sections, restricting TypeDoc's role as specified in the issue. TypeDoc tooling is updated to handle new generated documentation files with appropriate link mappings. Billing hooks are properly documented with JSDoc comments and exported types, fulfilling the requirement to include them in TypeDoc documentation.
Out of Scope Changes Check ✅ Passed All changes in the PR are directly scoped to the objective of enabling TypeDoc documentation for hook parameters and returns. File modifications include type exports with JSDoc documentation (commerce.tsx, contexts.tsx, useCheckout.ts, useReverification.ts, useSubscription.tsx), TypeDoc tooling updates (.typedoc/custom-plugin.mjs, new .typedoc/extract-returns-and-params.mjs script), a minor documentation update to a JSDoc description (billing.ts), and a changeset file. No unrelated refactoring, feature development, or bug fixes are present. A minor documentation-only update to a billing type description does not constitute scope creep.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch ss/DOCS-10983

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@SarahSoutoul SarahSoutoul changed the title Refactor Typedoc for hooks to support hook code examples on Clerk docs docs(repo): Refactor Typedoc for hooks to support hook code examples on Clerk docs Oct 1, 2025
@SarahSoutoul SarahSoutoul self-assigned this Oct 1, 2025
@SarahSoutoul SarahSoutoul changed the title docs(repo): Refactor Typedoc for hooks to support hook code examples on Clerk docs docs(repo): Generate all function params and return types Oct 2, 2025
@SarahSoutoul SarahSoutoul changed the title docs(repo): Generate all function params and return types docs(repo): Generate all params and return types (hooks work) Oct 2, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 12

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (5)
packages/shared/src/react/hooks/useSubscription.tsx (1)

78-85: Add explicit return type and JSDoc tags for the public hook

Public APIs must declare explicit return types and have clear JSDoc for params/returns.

Apply this diff:

 /**
  *
  * Fetches subscription data for the current user or organization.
  *
+ * @param params Options to control how subscription data is fetched.
+ * @returns Subscription data, loading/fetching flags, error, and a revalidate helper.
  * @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.
  */
-export const useSubscription = (params?: UseSubscriptionParams) => {
+export const useSubscription = (params?: UseSubscriptionParams): UseSubscriptionReturn => {

As per coding guidelines.

packages/shared/src/react/hooks/useReverification.ts (1)

165-212: Correct hook JSDoc: return type description and example variable name

  • The @returns text says “returns an array” but the hook returns a single enhanced fetcher function.
  • In the example, the catch variable is e but the condition checks err.

These affect developer trust and auto-generated docs.

- * @returns The `useReverification()` hook returns an array with the "enhanced" fetcher.
+ * @returns The `useReverification()` hook returns the "enhanced" fetcher function.
-    } catch (e) {
+    } catch (e) {
       // Handle error returned from the fetcher here
-
-      // You can also handle cancellation with the following
-      if (isReverificationCancelledError(err)) {
+      // You can also handle cancellation with the following
+      if (isReverificationCancelledError(e)) {
         // Handle the cancellation error here
       }
     }

Also applies to: 213-241

packages/types/src/billing.ts (2)

92-104: Using Exclude here is incorrect; use Omit to remove orgId from object types

Exclude<..., 'orgId'> does not remove a property; it filters union members. orgId is still allowed in these params. Replace with Omit<..., 'orgId'> to actually omit the key. This is a public type correctness issue.

-  initializePaymentMethod: (
-    params: Exclude<InitializePaymentMethodParams, 'orgId'>,
-  ) => Promise<BillingInitializedPaymentMethodResource>;
+  initializePaymentMethod: (
+    params: Omit<InitializePaymentMethodParams, 'orgId'>,
+  ) => Promise<BillingInitializedPaymentMethodResource>;

-  addPaymentMethod: (params: Exclude<AddPaymentMethodParams, 'orgId'>) => Promise<BillingPaymentMethodResource>;
+  addPaymentMethod: (params: Omit<AddPaymentMethodParams, 'orgId'>) => Promise<BillingPaymentMethodResource>;

-  getPaymentMethods: (
-    params: Exclude<GetPaymentMethodsParams, 'orgId'>,
-  ) => Promise<ClerkPaginatedResponse<BillingPaymentMethodResource>>;
+  getPaymentMethods: (
+    params: Omit<GetPaymentMethodsParams, 'orgId'>,
+  ) => Promise<ClerkPaginatedResponse<BillingPaymentMethodResource>>;

As per coding guidelines


784-787: JSDoc contradicts the type for freeTrialEndsAt

Doc states “Unix timestamp (milliseconds)” but the type is Date | null. Fix the description to match.

-  /**
-   * Unix timestamp (milliseconds) of when the free trial ends.
-   */
+  /**
+   * The date and time when the free trial ends.
+   */

Based on learnings

packages/shared/src/react/hooks/useCheckout.ts (1)

154-169: Remove extraneous status from fallback properties object

CheckoutProperties explicitly omits 'status', but the fallback literal includes status: null. This violates the declared type CheckoutProperties | ForceNull<CheckoutProperties> and will trigger excess property checks.

   const properties = useMemo<CheckoutProperties | ForceNull<CheckoutProperties>>(() => {
     if (!managerProperties.checkout) {
       return {
         id: null,
         externalClientSecret: null,
         externalGatewayId: null,
-        status: null,
         totals: null,
         isImmediatePlanChange: null,
         planPeriod: null,
         plan: null,
         paymentMethod: null,
         freeTrialEndsAt: null,
         payer: null,
       };
     }
🧹 Nitpick comments (24)
packages/shared/typedoc.json (1)

3-9: Use a recursive glob for hooks and verify duplicate symbols aren’t introduced

  • The single-level glob may miss nested hooks. Prefer a recursive glob.
  • Multiple entry points overlapping with exports from index.ts can produce duplicate symbols/pages in TypeDoc. Consider consolidating exports through index.ts or ensure no overlap.

Suggested change:

-    "./src/react/hooks/*.{ts,tsx}",
+    "./src/react/hooks/**/*.{ts,tsx}",

Please confirm:

  • Are any hooks nested in subfolders under src/react/hooks?
  • Does src/index.ts re-export any of react/types, react/hooks/*, react/commerce, or react/contexts, which could cause duplicates in the generated docs? If so, either remove the direct file entry points and rely on index.ts or adjust the exports to avoid duplication.
packages/shared/src/react/contexts.tsx (1)

28-46: Consider using interface instead of type, and remove the @interface JSDoc tag.

This type represents a simple object shape that could potentially be extended. Per the coding guidelines, interface should be preferred for such cases. Additionally, the @interface JSDoc tag is non-standard for TypeDoc—it automatically recognizes both interface and type declarations without requiring special annotations.

Apply this diff:

-/**
- * @interface
- */
-export type UseCheckoutOptions = {
+/**
+ * Options for configuring a checkout session.
+ */
+export interface UseCheckoutOptions {
   /**
    * Specifies if the checkout is for an organization.
    *
    * @default 'user'
    */
   for?: ForPayerType;
   /**
    * The billing period for the plan.
    */
   planPeriod: BillingSubscriptionPlanPeriod;
   /**
    * The ID of the subscription plan to check out (e.g. `cplan_xxx`).
    */
   planId: string;
-};
+}
packages/shared/src/react/commerce.tsx (3)

141-163: Consider using interface and improve wording on line 154.

Similar to UseCheckoutOptions, this is a simple object shape that should use interface per coding guidelines. The @interface JSDoc tag is unnecessary. Additionally, line 154's phrasing "whether to fetch for" is grammatically awkward.

Apply this diff:

-/**
- * @interface
- */
-export type PaymentElementProviderProps = {
+/**
+ * Props for the PaymentElementProvider component.
+ */
+export interface PaymentElementProviderProps {
   /**
    * An optional checkout resource object. When provided, the payment element is scoped to the specific checkout session.
    */
   checkout?: BillingCheckoutResource;
   /**
    * An optional object to customize the appearance of the Stripe Payment Element. This allows you to match the form's styling to your application's theme.
    */
   stripeAppearance?: internalStripeAppearance;
   /**
-   * Specifies whether to fetch for the current user or organization.
+   * Specifies whether the payment element is for the current user or organization.
    *
    * @default 'user'
    */
   for?: ForPayerType;
   /**
    * An optional description to display to the user within the payment element UI.
    */
   paymentDescription?: string;
-};
+}

243-251: Consider using interface instead of type, and remove the @interface JSDoc tag.

Consistent with the previous suggestions, this simple object shape should use interface per coding guidelines, and the @interface JSDoc tag is unnecessary.

Apply this diff:

-/**
- * @interface
- */
-export type PaymentElementProps = {
+/**
+ * Props for the PaymentElement component.
+ */
+export interface PaymentElementProps {
   /**
    * Optional fallback content, such as a loading skeleton, to display while the payment form is being initialized.
    */
   fallback?: ReactNode;
-};
+}

320-362: Remove the @interface JSDoc tag.

Unlike the previous types, this discriminated union is appropriately declared as a type (not interface) per coding guidelines, since it combines unions with object shapes. However, the @interface JSDoc tag is still unnecessary—TypeDoc will correctly document this type without it.

Apply this diff:

 /**
- * @interface
+ * Return type for the usePaymentElement hook.
  */
 export type UsePaymentElementReturn = {
packages/shared/src/react/hooks/usePlans.tsx (1)

27-30: Fix JSDoc tag and ensure public export for Typedoc visibility

  • @interface on a type alias is incorrect and can confuse Typedoc. Add a short description and mark as @public.
  • If usePlans is @internal, ensure the return type you expose is what you intend to document publicly.
  • Export this type from the hooks barrel so Typedoc picks it up.

Apply:

-/**
- * @interface
- */
-export type UsePlansReturn = ReturnType<typeof usePlans>;
+/**
+ * Return type of the usePlans hook.
+ *
+ * @public
+ * @see usePlans
+ */
+export type UsePlansReturn = ReturnType<typeof usePlans>;

If createBillingPaginatedHook exposes a public generic result type (e.g., BillingPaginatedResult), prefer an explicit alias for clearer docs:

export type UsePlansReturn = BillingPaginatedResult<BillingPlanResource, GetPlansParams>;

Also update the barrel (packages/shared/src/react/hooks/index.ts):

export type { UsePlansReturn } from './usePlans';

Please confirm that UsePlansReturn appears in the generated Typedoc and renders the full shape (not just ReturnType<...>). If it doesn’t, consider the explicit alias approach above.

packages/types/src/clerk.ts (1)

82-84: Add a brief description before @inline
@inline is supported natively since TypeDoc v0.27.0 and will inline this union in the generated docs. Consider adding a one-line summary for clarity:

 /**
- * @inline
+ * Result of checkout operations for `start`/`confirm`.
+ * @inline
  */
packages/shared/src/react/types.ts (4)

116-121: Remove stray blank line in JSDoc to avoid extra paragraph in TypeDoc.
Small cleanup for consistent rendering.

  * @default undefined
  *
  * @hidden
- *
  * @experimental
  */

7-9: Avoid any in public types; prefer unknown as default.
Aligns with project guidelines and safer typing.

As per coding guidelines

-export type CacheSetter<CData = any> = (
+export type CacheSetter<CData = unknown> = (
   data?: CData | ((currentData?: CData) => Promise<undefined | CData> | undefined | CData),
 ) => Promise<CData | undefined>;

52-56: Fix off‑by‑one in JSDoc example for previous page (1‑based paging).
initialPage defaults to 1; previous page lower bound should be 1, not 0.

- * A function that triggers the previous page to be loaded. This is the same as `fetchPage(page => Math.max(0, page - 1))`.
+ * A function that triggers the previous page to be loaded. This is the same as `fetchPage(page => Math.max(1, page - 1))`.

82-85: Update stale comment to match type name.
Clarify doc to reflect PaginatedResources.

-// Utility type to convert PaginatedDataAPI to properties as undefined, except booleans set to false
+// Utility type to convert PaginatedResources to properties as undefined, except booleans set to false
packages/shared/src/react/hooks/useSubscription.tsx (2)

123-124: Make revalidate truly return Promise<void> and stabilize deps

mutate() resolves to Promise<Data | undefined>. Either reflect that in the type or wrap to return Promise<void>. Also prefer [swr] over [swr.mutate].

Apply this diff:

-  const revalidate = useCallback(() => swr.mutate(), [swr.mutate]);
+  const revalidate = useCallback(async () => {
+    await swr.mutate();
+  }, [swr]);

15-18: Remove non-standard @interface tags from JSDoc

@interface isn’t a TSDoc/TypeDoc tag and adds noise. Remove or replace with @public if needed.

Apply this diff:

-/**
- * @interface
- */
+/** */
@@
-/**
- * @interface
- */
+/** */
@@
-/**
- * @interface
- */
+/** */

Also applies to: 33-35, 43-45

.typedoc/extract-returns-and-params.mjs (4)

69-86: Handle “## Properties” fallback and normalize heading to “## Parameters”.

Some hooks render “Properties” instead of “Parameters”. Extract either, and when extracting “Properties”, rename the heading to “Parameters” for consistency.

Apply this diff:

-  // Find the "## Parameters" section
-  const paramsStart = content.indexOf('## Parameters');
+  // Find the "## Parameters" or "## Properties" section
+  const headingOptions = ['## Parameters', '## Properties'];
+  let headingUsed = '';
+  let paramsStart = -1;
+  for (const h of headingOptions) {
+    const idx = content.indexOf(h);
+    if (idx !== -1) {
+      headingUsed = h;
+      paramsStart = idx;
+      break;
+    }
+  }
 
   if (paramsStart === -1) {
     return false; // No Parameters section found
   }
 
-  // Find the next heading after "## Parameters" (or end of file)
-  const afterParams = content.slice(paramsStart + 13); // Skip past "## Parameters"
-  const nextHeadingMatch = afterParams.match(/\n## /);
+  // Find the next "## " heading after the found section (or end of file)
+  const headingLen = headingUsed.length;
+  const afterParams = content.slice(paramsStart + headingLen);
+  const nextHeadingMatch = afterParams.match(/(?:\r?\n)##\s/);
   const paramsEnd =
-    nextHeadingMatch && typeof nextHeadingMatch.index === 'number'
-      ? paramsStart + 13 + nextHeadingMatch.index
+    nextHeadingMatch && typeof nextHeadingMatch.index === 'number'
+      ? paramsStart + headingLen + nextHeadingMatch.index
       : content.length;
 
-  // Extract the Parameters section and trim trailing whitespace
-  const paramsContent = content.slice(paramsStart, paramsEnd).trimEnd();
+  // Extract the section and normalize heading to "## Parameters"
+  let paramsContent = content.slice(paramsStart, paramsEnd).trimEnd();
+  if (headingUsed === '## Properties') {
+    paramsContent = paramsContent.replace(/^## Properties\b/m, '## Parameters');
+  }

25-30: CRLF-safe next-heading detection for “Returns”.

Make heading detection robust across line endings and spacing.

Apply this diff:

-  // Find the next heading after "## Returns" (or end of file)
-  const afterReturns = content.slice(returnsStart + 10); // Skip past "## Returns"
-  const nextHeadingMatch = afterReturns.match(/\n## /);
+  // Find the next "## " heading after "## Returns" (or end of file)
+  const afterReturns = content.slice(returnsStart + 10); // Skip past "## Returns"
+  const nextHeadingMatch = afterReturns.match(/(?:\r?\n)##\s/);

128-134: Avoid hard-coding packages; discover under temp-docs.

To support more SDKs (e.g., nextjs, expo) without code changes, derive packages from temp-docs.

Example:

-function main() {
-  const packages = ['clerk-react'];
-  const dirs = packages.map(folder => path.join(__dirname, 'temp-docs', folder));
+function main() {
+  const docsRoot = path.join(__dirname, 'temp-docs');
+  const packages = fs.existsSync(docsRoot)
+    ? fs.readdirSync(docsRoot, { withFileTypes: true }).filter(d => d.isDirectory()).map(d => d.name)
+    : [];
+  const dirs = packages.map(folder => path.join(docsRoot, folder));

9-15: DRY the section-extraction logic.

extractReturnsSection and extractParametersSection share most logic (find heading, find next “## ”, slice, write). Consider a single helper: extractSection(filePath, { headingNames, outSuffix, deleteOldSuffixes?, normalize? }).

Also applies to: 47-55

packages/shared/src/react/hooks/createBillingPaginatedHook.tsx (1)

27-29: Use @typedef instead of @interface for type aliases.

The @interface JSDoc tag is intended for interface declarations. Since HookParams is defined using the type keyword (a type alias), consider using @typedef instead, or omit the tag entirely and let Typedoc infer the correct kind.

Apply this diff:

 /**
- * @interface
+ * @typedef HookParams
  */
 export type HookParams = PaginatedHookConfig<PagesOrInfiniteOptions> & {

Or simply remove the tag:

-/**
- * @interface
- */
 export type HookParams = PaginatedHookConfig<PagesOrInfiniteOptions> & {
.typedoc/custom-plugin.mjs (1)

46-49: Anchor-only replacements can produce double anchors

Mapping to "#use-..." while preserving the original anchor yields "#use-...#something". If anchors are ever present on source links, drop the captured anchor when newPath starts with "#".

Suggested change (outside this hunk) in getRelativeLinkReplacements:

-      replace: (/** @type {string} */ _match, anchor = '') => `(${newPath}${anchor})`,
+      replace: (/** @type {string} */ _match, anchor = '') =>
+        `(${newPath}${newPath.startsWith('#') ? '' : anchor})`,

Also confirm the target headings exist for:

  • #use-checkout-options
  • #use-reverification-options
  • #needs-reverification-parameters
packages/shared/src/react/hooks/useReverification.ts (2)

14-16: Remove or complete empty JSDoc; mark internal helpers explicitly

This empty block will surface as noise in Typedoc. Either document resolveResult properly and mark it @internal, or remove the block.

-/**
- *
- */
+/**
+ * @internal
+ * Normalize a fetcher result by unwrapping `Response` bodies and converting Clerk reverification API errors
+ * into a reverification hint.
+ *
+ * @template T
+ * @param result A promise or value returned by a fetcher.
+ * @returns The resolved value, or a reverification hint wrapper.
+ */

95-101: Document internal helpers or remove placeholder blocks

createReverificationHandler/assertReverification are internal. Empty JSDoc blocks reduce clarity and pollute docs.

-/**
- */
+/**
+ * @internal
+ * Creates a handler that wraps a fetcher with a reverification flow.
+ */
 function createReverificationHandler(params: CreateReverificationHandlerParams) {
-  /**
-   *
-   */
+  /**
+   * @internal
+   * Wraps a fetcher to intercept reverification hints, show UI or call the custom handler,
+   * and retry the original fetch on success.
+   */
   function assertReverification<Fetcher extends (...args: any[]) => Promise<any> | undefined>(
packages/types/src/billing.ts (2)

705-731: Strengthen ConfirmCheckoutParams to enforce mutual exclusivity and required fields

Current union members use optional fields, allowing {} and not enforcing the “only one of …” rule. Make fields required per branch and model the XOR intent.

-export type ConfirmCheckoutParams =
-  | {
-      /**
-       * The ID of a saved payment method to use for this checkout.
-       */
-      paymentSourceId?: string;
-    }
-  | {
-      /**
-       * A token representing payment details, usually from a payment form. **Requires** `gateway` to be provided.
-       */
-      paymentToken?: string;
-      /**
-       * The payment gateway to use. **Required** if `paymentToken` or `useTestCard` is provided.
-       */
-      gateway?: PaymentGateway;
-    }
-  | {
-      /**
-       * The payment gateway to use. **Required** if `paymentToken` or `useTestCard` is provided.
-       */
-      gateway?: PaymentGateway;
-      /**
-       * If true, uses a test card for the checkout. **Requires** `gateway` to be provided.
-       */
-      useTestCard?: boolean;
-    };
+export type ConfirmCheckoutParams =
+  | {
+      /** The ID of a saved payment method to use for this checkout. */
+      paymentSourceId: string;
+    }
+  | {
+      /** A token representing payment details, usually from a payment form. */
+      paymentToken: string;
+      /** The payment gateway to use. */
+      gateway: PaymentGateway;
+    }
+  | {
+      /** The payment gateway to use. */
+      gateway: PaymentGateway;
+      /** If true, uses a test card for the checkout. */
+      useTestCard: boolean;
+    };

As per coding guidelines


309-309: Prefer optional property over string | undefined

For consistency with the rest of the file, use walletType?: string instead of string | undefined.

-  walletType: string | undefined;
+  walletType?: string;

As per coding guidelines

packages/shared/src/react/hooks/useCheckout.ts (1)

114-121: Consider adding @returns in function JSDoc for public API completeness

To meet “All public APIs must be documented with JSDoc,” add a returns description for useCheckout.

 /**
  * @function
  *
  * @param [options] - An object containing the configuration for the checkout flow.
  *
  * **Required** if the hook is used without a `<CheckoutProvider />` wrapping the component tree.
+ *
+ * @returns An object containing the `checkout` API with typed status, data, and actions.
  */
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 29201b2 and 038c99d.

📒 Files selected for processing (19)
  • .typedoc/custom-plugin.mjs (3 hunks)
  • .typedoc/extract-returns-and-params.mjs (1 hunks)
  • package.json (1 hunks)
  • packages/shared/src/errors/clerkApiResponseError.ts (1 hunks)
  • packages/shared/src/react/commerce.tsx (4 hunks)
  • packages/shared/src/react/contexts.tsx (1 hunks)
  • packages/shared/src/react/hooks/createBillingPaginatedHook.tsx (1 hunks)
  • packages/shared/src/react/hooks/useCheckout.ts (2 hunks)
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx (1 hunks)
  • packages/shared/src/react/hooks/usePaymentMethods.tsx (1 hunks)
  • packages/shared/src/react/hooks/usePlans.tsx (1 hunks)
  • packages/shared/src/react/hooks/useReverification.ts (4 hunks)
  • packages/shared/src/react/hooks/useSession.ts (0 hunks)
  • packages/shared/src/react/hooks/useStatements.tsx (1 hunks)
  • packages/shared/src/react/hooks/useSubscription.tsx (2 hunks)
  • packages/shared/src/react/types.ts (1 hunks)
  • packages/shared/typedoc.json (1 hunks)
  • packages/types/src/billing.ts (1 hunks)
  • packages/types/src/clerk.ts (1 hunks)
🔥 Files not summarized due to errors (16)
  • packages/shared/src/errors/clerkApiResponseError.ts: Error: Server error: no LLM provider could handle the message
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx: Error: Server error: no LLM provider could handle the message
  • packages/shared/src/react/types.ts: Error: Server error: no LLM provider could handle the message
  • .typedoc/custom-plugin.mjs: Error: Server error: no LLM provider could handle the message
  • .typedoc/extract-returns-and-params.mjs: Error: Server error: no LLM provider could handle the message
  • packages/shared/src/react/hooks/usePaymentMethods.tsx: Error: Server error: no LLM provider could handle the message
  • packages/shared/src/react/hooks/useSubscription.tsx: Error: Server error: no LLM provider could handle the message
  • packages/shared/src/react/hooks/useReverification.ts: Error: Server error: no LLM provider could handle the message
  • packages/shared/src/react/hooks/useSession.ts: Error: Server error: no LLM provider could handle the message
  • packages/shared/src/react/hooks/usePlans.tsx: Error: Server error: no LLM provider could handle the message
  • packages/shared/typedoc.json: Error: Server error: no LLM provider could handle the message
  • package.json: Error: Server error: no LLM provider could handle the message
  • packages/shared/src/react/hooks/createBillingPaginatedHook.tsx: Error: Server error: no LLM provider could handle the message
  • packages/shared/src/react/hooks/useStatements.tsx: Error: Server error: no LLM provider could handle the message
  • packages/shared/src/react/hooks/useCheckout.ts: Error: Server error: no LLM provider could handle the message
  • packages/types/src/clerk.ts: Error: Server error: no LLM provider could handle the message
💤 Files with no reviewable changes (1)
  • packages/shared/src/react/hooks/useSession.ts
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx
  • packages/shared/src/react/types.ts
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/shared/src/react/hooks/useSubscription.tsx
  • packages/shared/src/react/hooks/useReverification.ts
  • packages/shared/src/react/hooks/usePlans.tsx
  • packages/shared/src/react/hooks/createBillingPaginatedHook.tsx
  • packages/shared/src/react/hooks/useStatements.tsx
  • packages/shared/src/react/hooks/useCheckout.ts
  • packages/types/src/billing.ts
  • packages/shared/src/react/contexts.tsx
  • packages/types/src/clerk.ts
  • packages/shared/src/react/commerce.tsx
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx
  • packages/shared/src/react/types.ts
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/shared/src/react/hooks/useSubscription.tsx
  • packages/shared/src/react/hooks/useReverification.ts
  • packages/shared/src/react/hooks/usePlans.tsx
  • packages/shared/typedoc.json
  • package.json
  • packages/shared/src/react/hooks/createBillingPaginatedHook.tsx
  • packages/shared/src/react/hooks/useStatements.tsx
  • packages/shared/src/react/hooks/useCheckout.ts
  • packages/types/src/billing.ts
  • packages/shared/src/react/contexts.tsx
  • packages/types/src/clerk.ts
  • packages/shared/src/react/commerce.tsx
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx
  • packages/shared/src/react/types.ts
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/shared/src/react/hooks/useSubscription.tsx
  • packages/shared/src/react/hooks/useReverification.ts
  • packages/shared/src/react/hooks/usePlans.tsx
  • packages/shared/src/react/hooks/createBillingPaginatedHook.tsx
  • packages/shared/src/react/hooks/useStatements.tsx
  • packages/shared/src/react/hooks/useCheckout.ts
  • packages/types/src/billing.ts
  • packages/shared/src/react/contexts.tsx
  • packages/types/src/clerk.ts
  • packages/shared/src/react/commerce.tsx
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx
  • packages/shared/src/react/types.ts
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/shared/src/react/hooks/useSubscription.tsx
  • packages/shared/src/react/hooks/useReverification.ts
  • packages/shared/src/react/hooks/usePlans.tsx
  • packages/shared/src/react/hooks/createBillingPaginatedHook.tsx
  • packages/shared/src/react/hooks/useStatements.tsx
  • packages/shared/src/react/hooks/useCheckout.ts
  • packages/types/src/billing.ts
  • packages/shared/src/react/contexts.tsx
  • packages/types/src/clerk.ts
  • packages/shared/src/react/commerce.tsx
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx
  • packages/shared/src/react/types.ts
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/shared/src/react/hooks/useSubscription.tsx
  • packages/shared/src/react/hooks/useReverification.ts
  • packages/shared/src/react/hooks/usePlans.tsx
  • packages/shared/src/react/hooks/createBillingPaginatedHook.tsx
  • packages/shared/src/react/hooks/useStatements.tsx
  • packages/shared/src/react/hooks/useCheckout.ts
  • packages/types/src/billing.ts
  • packages/shared/src/react/contexts.tsx
  • packages/types/src/clerk.ts
  • packages/shared/src/react/commerce.tsx
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/react/hooks/usePaymentAttempts.tsx
  • packages/shared/src/react/types.ts
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/shared/src/react/hooks/useSubscription.tsx
  • packages/shared/src/react/hooks/useReverification.ts
  • packages/shared/src/react/hooks/usePlans.tsx
  • packages/shared/src/react/hooks/createBillingPaginatedHook.tsx
  • packages/shared/src/react/hooks/useStatements.tsx
  • packages/shared/src/react/hooks/useCheckout.ts
  • packages/types/src/billing.ts
  • packages/shared/src/react/contexts.tsx
  • packages/types/src/clerk.ts
  • packages/shared/src/react/commerce.tsx
**/*.{jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{jsx,tsx}: Use error boundaries in React components
Minimize re-renders in React components

**/*.{jsx,tsx}: Always use functional components with hooks instead of class components
Follow PascalCase naming for components: UserProfile, NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...

Files:

  • packages/shared/src/react/hooks/usePaymentAttempts.tsx
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/shared/src/react/hooks/useSubscription.tsx
  • packages/shared/src/react/hooks/usePlans.tsx
  • packages/shared/src/react/hooks/createBillingPaginatedHook.tsx
  • packages/shared/src/react/hooks/useStatements.tsx
  • packages/shared/src/react/contexts.tsx
  • packages/shared/src/react/commerce.tsx
**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/react.mdc)

**/*.tsx: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering

Files:

  • packages/shared/src/react/hooks/usePaymentAttempts.tsx
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/shared/src/react/hooks/useSubscription.tsx
  • packages/shared/src/react/hooks/usePlans.tsx
  • packages/shared/src/react/hooks/createBillingPaginatedHook.tsx
  • packages/shared/src/react/hooks/useStatements.tsx
  • packages/shared/src/react/contexts.tsx
  • packages/shared/src/react/commerce.tsx
🧬 Code graph analysis (10)
packages/shared/src/react/hooks/usePaymentAttempts.tsx (2)
packages/clerk-js/src/ui/contexts/components/Plans.tsx (1)
  • usePaymentAttempts (42-50)
packages/shared/src/react/hooks/index.ts (1)
  • usePaymentAttempts (12-12)
packages/shared/src/react/hooks/usePaymentMethods.tsx (2)
packages/clerk-js/src/ui/contexts/components/Plans.tsx (1)
  • usePaymentMethods (32-40)
packages/shared/src/react/hooks/index.ts (1)
  • usePaymentMethods (13-13)
packages/shared/src/react/hooks/useSubscription.tsx (1)
packages/types/src/billing.ts (2)
  • ForPayerType (69-69)
  • BillingSubscriptionResource (565-615)
packages/shared/src/react/hooks/useReverification.ts (2)
packages/types/src/sessionVerification.ts (1)
  • SessionVerificationLevel (50-50)
packages/types/src/clerk.ts (1)
  • Clerk (168-899)
packages/shared/src/react/hooks/usePlans.tsx (2)
packages/clerk-js/src/ui/contexts/components/Plans.tsx (1)
  • usePlans (80-90)
packages/shared/src/react/hooks/index.ts (1)
  • usePlans (14-14)
packages/shared/src/react/hooks/createBillingPaginatedHook.tsx (2)
packages/shared/src/react/types.ts (2)
  • PaginatedHookConfig (90-103)
  • PagesOrInfiniteOptions (134-157)
packages/types/src/billing.ts (1)
  • ForPayerType (69-69)
packages/shared/src/react/hooks/useStatements.tsx (2)
packages/clerk-js/src/ui/contexts/components/Plans.tsx (1)
  • useStatements (52-61)
packages/shared/src/react/hooks/index.ts (1)
  • useStatements (11-11)
packages/shared/src/react/hooks/useCheckout.ts (3)
packages/types/src/billing.ts (1)
  • BillingCheckoutResource (738-791)
packages/shared/src/error.ts (1)
  • ClerkAPIResponseError (4-4)
packages/types/src/clerk.ts (3)
  • __experimental_CheckoutCacheState (67-74)
  • __experimental_CheckoutInstance (95-102)
  • SetActiveNavigate (127-127)
packages/shared/src/react/contexts.tsx (1)
packages/types/src/billing.ts (2)
  • ForPayerType (69-69)
  • BillingSubscriptionPlanPeriod (83-83)
packages/shared/src/react/commerce.tsx (1)
packages/types/src/billing.ts (2)
  • BillingCheckoutResource (738-791)
  • ForPayerType (69-69)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (7)
packages/shared/src/react/hooks/useStatements.tsx (1)

21-24: Replace non-standard @interface tag; add TSDoc description and visibility

@interface isn’t recognized by TypeDoc; use a concise description and explicit @public:

-/**
- * @interface
- */
+/**
+ * Named return type for useStatements.
+ * @public
+ */
 export type UseStatementsReturn = ReturnType<typeof useStatements>;

Optional: alias to the concrete return type (e.g., BillingPaginatedHookReturn<BillingStatementResource, GetStatementsParams>) to improve readability in generated docs.

Please run Typedoc generation to confirm no unknown-tag warnings and correct rendering of this alias.

packages/shared/src/react/types.ts (1)

87-103: Confirm Typedoc handling of @inline/@interface for consistent headings.
To resolve “Parameters” vs “Properties” inconsistencies, verify these tags are recognized by your Typedoc setup (plugins/config).

Based on PR objectives

packages/shared/src/react/hooks/useSubscription.tsx (1)

19-31: Doc default behavior for for is correct; type is good

Defaulting to user when for !== 'organization' matches the code path. No changes needed.

If there are future payer types beyond 'user' | 'organization', consider making the default explicit: const isOrganization = params?.for === 'organization'; (already implemented).

.typedoc/custom-plugin.mjs (1)

82-89: All new doc links resolve (HTTP 200)

packages/shared/src/react/hooks/useCheckout.ts (3)

30-33: Typedoc @inline tag usage — verify support in pipeline

@inline isn’t a core Typedoc tag. Please confirm your current Typedoc setup recognizes it (plugin or custom renderer), otherwise it will be ignored.

Would you like me to generate a quick script to grep for the Typedoc config/plugins in the repo to confirm support?


35-52: Typed union for error/fetchStatus looks good

The discriminated union cleanly models error vs fetchStatus. Matches __experimental_CheckoutCacheState.


61-70: Status documentation is clear and actionable

The status list is precise and aligns with expected flow (startconfirmfinalize).

Comment on lines 22 to 36
'use-checkout-return.mdx',
'use-checkout-options.mdx',
'use-payment-element-return.mdx',
'use-payment-element-return.mdx',
'use-payment-methods-return.mdx',
'use-payment-attempts-return.mdx',
'use-plans-return.mdx',
'use-statements-return.mdx',
'hook-params.mdx',
'use-subscription-params.mdx',
'use-subscription-return.mdx',
'needs-reverification-parameters.mdx',
'use-reverification-options.mdx',
'use-reverification-params,mdx',
];
Copy link
Contributor

@coderabbitai coderabbitai bot Oct 15, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Fix typo and remove duplicate in FILES_WITHOUT_HEADINGS

  • Typo: "use-reverification-params,mdx" should be ".mdx" (prevents headings removal on that page).
  • Duplicate: "use-payment-element-return.mdx" appears twice.

Apply:

   'use-payment-element-return.mdx',
-  'use-payment-element-return.mdx',
   'use-payment-methods-return.mdx',
@@
-  'use-reverification-params,mdx',
+  'use-reverification-params.mdx',
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
'use-checkout-return.mdx',
'use-checkout-options.mdx',
'use-payment-element-return.mdx',
'use-payment-element-return.mdx',
'use-payment-methods-return.mdx',
'use-payment-attempts-return.mdx',
'use-plans-return.mdx',
'use-statements-return.mdx',
'hook-params.mdx',
'use-subscription-params.mdx',
'use-subscription-return.mdx',
'needs-reverification-parameters.mdx',
'use-reverification-options.mdx',
'use-reverification-params,mdx',
];
'use-checkout-return.mdx',
'use-checkout-options.mdx',
'use-payment-element-return.mdx',
'use-payment-methods-return.mdx',
'use-payment-attempts-return.mdx',
'use-plans-return.mdx',
'use-statements-return.mdx',
'hook-params.mdx',
'use-subscription-params.mdx',
'use-subscription-return.mdx',
'needs-reverification-parameters.mdx',
'use-reverification-options.mdx',
'use-reverification-params.mdx',
];
🤖 Prompt for AI Agents
In .typedoc/custom-plugin.mjs around lines 22 to 36, the FILES_WITHOUT_HEADINGS
array contains a typo and a duplicate entry: change
"use-reverification-params,mdx" to "use-reverification-params.mdx" and remove
the repeated "use-payment-element-return.mdx" so each filename appears once;
update the array accordingly to include the corrected filename and only one
instance of each file.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check the specific commit to verify the fixes were applied
git show 45f698d2ec80f8c08de92367b1dba9ed1101bcd1 -- .typedoc/custom-plugin.mjs

Length of output: 917


🏁 Script executed:

#!/bin/bash
# Check the current state of the file to verify all fixes
cat .typedoc/custom-plugin.mjs | grep -A 2 -B 2 "use-reverification-params"

Length of output: 115


@SarahSoutoul, thank you for addressing the duplicate! I can confirm that use-payment-element-return.mdx now appears only once. 👍

However, I notice the typo on Line 34 still needs to be fixed:

  • Current: 'use-reverification-params,mdx' (has a comma)
  • Should be: 'use-reverification-params.mdx' (needs a period)

This will ensure the heading removal works correctly for that file.


🧬 Code Graph Analysis Results

[typedoc/custom-router.mjs] lines 26-28

export function load(app) {
  app.renderer.defineRouter('clerk-router', ClerkRouter);
}

[typedoc/custom-theme.mjs] lines 8-10

export function load(app) {
  app.renderer.defineTheme('clerkTheme', ClerkMarkdownTheme);
}

Comment on lines +48 to +56
* Extracts the "## Parameters" section from a markdown file and writes it to a separate file.
* @param {string} filePath - The path to the markdown file
* @param {string} dirName - The directory containing the files
* @returns {boolean} True if a file was created
*/
function extractParametersSection(filePath, dirName) {
const content = fs.readFileSync(filePath, 'utf-8');
const fileName = path.basename(filePath, '.mdx');

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Params written to wrong directory; props deletion path wrong (critical).

extractParametersSection writes -params.mdx at the package root and deletes -props.mdx there, not next to the source file. This will misplace files for nested MDX and fail to delete the actual props file. Align with extractReturnsSection by using the file’s own directory and drop the extra dirName param.

Apply these diffs:

- * @param {string} dirName - The directory containing the files
  * @returns {boolean} True if a file was created
  */
-function extractParametersSection(filePath, dirName) {
+function extractParametersSection(filePath) {
-  // Delete any existing -props file (TypeDoc-generated)
-  const propsFilePath = path.join(dirName, propsFileName);
+  // Delete any existing -props file (TypeDoc-generated)
+  const dirForFile = path.dirname(filePath);
+  const propsFilePath = path.join(dirForFile, propsFileName);
-  // Write to new file
-  const newFilePath = path.join(dirName, targetFileName);
+  // Write to new file (next to source)
+  const newFilePath = path.join(dirForFile, targetFileName);
   fs.writeFileSync(newFilePath, paramsContent, 'utf-8');
-      // Extract Parameters sections
-      if (extractParametersSection(filePath, dir)) {
+      // Extract Parameters sections
+      if (extractParametersSection(filePath)) {
         paramsCount++;
       }

Also applies to: 62-67, 87-90, 154-156

🤖 Prompt for AI Agents
In .typedoc/extract-returns-and-params.mjs around lines 48-56 (and also update
the similar blocks at 62-67, 87-90, and 154-156): the function currently writes
the -params.mdx file to the package root and deletes the -props.mdx from the
wrong location because it uses the passed dirName; change the logic to derive
the target directory from the source file itself (use path.dirname(filePath))
and remove the extra dirName parameter so the new -params.mdx is written next to
the source MDX and the corresponding -props.mdx deletion targets the same
directory, mirroring the behavior of extractReturnsSection.

"turbo:clean": "turbo daemon clean",
"typedoc:generate": "pnpm build:declarations && pnpm typedoc:generate:skip-build",
"typedoc:generate:skip-build": "typedoc --tsconfig tsconfig.typedoc.json && rm -rf .typedoc/docs && mv .typedoc/temp-docs .typedoc/docs",
"typedoc:generate:skip-build": "typedoc --tsconfig tsconfig.typedoc.json && node .typedoc/extract-returns-and-params.mjs && rm -rf .typedoc/docs && mv .typedoc/temp-docs .typedoc/docs",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Make script cross‑platform (avoid POSIX rm/mv).

rm -rf and mv break on Windows. Use existing rimraf and cpy-cli instead.

Apply this diff:

-"typedoc:generate:skip-build": "typedoc --tsconfig tsconfig.typedoc.json && node .typedoc/extract-returns-and-params.mjs && rm -rf .typedoc/docs && mv .typedoc/temp-docs .typedoc/docs",
+"typedoc:generate:skip-build": "typedoc --tsconfig tsconfig.typedoc.json && node .typedoc/extract-returns-and-params.mjs && rimraf .typedoc/docs && cpy \".typedoc/temp-docs/**\" .typedoc/docs --parents && rimraf .typedoc/temp-docs",
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
"typedoc:generate:skip-build": "typedoc --tsconfig tsconfig.typedoc.json && node .typedoc/extract-returns-and-params.mjs && rm -rf .typedoc/docs && mv .typedoc/temp-docs .typedoc/docs",
"typedoc:generate:skip-build": "typedoc --tsconfig tsconfig.typedoc.json && node .typedoc/extract-returns-and-params.mjs && rimraf .typedoc/docs && cpy \".typedoc/temp-docs/**\" .typedoc/docs --parents && rimraf .typedoc/temp-docs",
🤖 Prompt for AI Agents
In package.json at line 60, the typedoc:generate:skip-build script uses
POSIX-only rm and mv which fail on Windows; update the script to use the
project's cross-platform tools (rimraf to remove .typedoc/docs and cpy-cli to
move or copy .typedoc/temp-docs into .typedoc/docs) and ensure flags preserve
recursive behavior; keep the existing typedoc and node steps, then run rimraf
.typedoc/docs and use cpy (or cpy-cli) to copy all files from .typedoc/temp-docs
to .typedoc/docs, and finally remove .typedoc/temp-docs with rimraf if desired.

Comment on lines +15 to +17
/**
* Interface representing a Clerk API Response Error.
*/
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

🧩 Analysis chain

JSDoc mismatch: refers to “Interface” but documents a class; enrich for Typedoc

Replace the summary and add basic tags to align with the PR goal (Typedoc metadata).

Apply this diff:

-/**
- * Interface representing a Clerk API Response Error.
- */
+/**
+ * Class representing a Clerk API response error thrown when the Clerk API returns an error payload.
+ * @public
+ * @remarks Use `status`, `errors`, `clerkTraceId`, and `retryAfter` to inspect details.
+ * @see isClerkApiResponseError
+ */

Additionally (outside this range), consider:

  • Add JSDoc to public fields so Typedoc shows property descriptions.
  • Add explicit return types to methods to satisfy coding guidelines.

Example snippet:

export class ClerkAPIResponseError extends ClerkError implements ClerkAPIResponseErrorInterface {
  /** HTTP status code returned by the API. */
  public status: number;

  /** Unique trace identifier for support/debugging. */
  public clerkTraceId?: string;

  /** Retry-After value (in seconds) when rate limited or similar. */
  public retryAfter?: number;

  /** Parsed list of API errors. */
  public errors: ClerkAPIError[];

  /** Returns a stringified representation of this error. */
  public toString(): string { /* unchanged body */ }

  // Keeps message unformatted for backward compatibility
  protected static override formatMessage(name: string, msg: string, _: string, __: string | undefined): string {
    return msg;
  }
}

Please re-run your Typedoc flow (pnpm run typedoc:generate) to confirm the class and its members render with the updated descriptions, and that constructor params/fields appear as expected. As per coding guidelines.


🏁 Script executed:

#!/bin/bash
file=$(fd clerkApiResponseError.ts)
echo "Found file: $file"
sed -n '1,30p' "$file"

Length of output: 1203


🏁 Script executed:

#!/bin/bash
file="packages/shared/src/errors/clerkApiResponseError.ts"
sed -n '30,100p' "$file"

Length of output: 1081


Fix JSDoc header and document public API

Replace at packages/shared/src/errors/clerkApiResponseError.ts (lines 15–17):

-/**
- * Interface representing a Clerk API Response Error.
- */
+/**
+ * Class representing a Clerk API response error thrown when the Clerk API returns an error payload.
+ * @public
+ * @remarks Use `status`, `errors`, `clerkTraceId`, and `retryAfter` to inspect details.
+ * @see isClerkApiResponseError
+ */
  • Add JSDoc comments to each public property (status, clerkTraceId, retryAfter, errors).
  • Annotate toString() and protected static override formatMessage() with an explicit : string return type.
    [must_fix]
🤖 Prompt for AI Agents
In packages/shared/src/errors/clerkApiResponseError.ts around lines 15 to 17,
the file is missing JSDoc on public properties and explicit return type
annotations on two methods; add clear JSDoc comments above each public property
(status, clerkTraceId, retryAfter, errors) describing type and purpose, and
update the method signatures of toString() and the protected static override
formatMessage() to include an explicit ": string" return type; ensure the JSDoc
uses standard /** ... */ format and mentions visibility (public) where
appropriate.

Comment on lines +23 to +26
/**
* @interface
*/
export type UsePaymentMethodsReturn = ReturnType<typeof usePaymentMethods>;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Fix JSDoc tag and also export Params type for Typedoc

  • @interface is incorrect on a type alias; replace with a short description (optionally @public).
  • Expose parameters via a UsePaymentMethodsParams alias so docs can render both returns and params.
-/**
- * @interface
- */
-export type UsePaymentMethodsReturn = ReturnType<typeof usePaymentMethods>;
+/**
+ * Typed return of usePaymentMethods.
+ * @public
+ */
+export type UsePaymentMethodsReturn = ReturnType<typeof usePaymentMethods>;
+
+/**
+ * Typed params accepted by usePaymentMethods.
+ * @public
+ */
+export type UsePaymentMethodsParams = Parameters<typeof usePaymentMethods>[0];
🤖 Prompt for AI Agents
In packages/shared/src/react/hooks/usePaymentMethods.tsx around lines 23 to 26,
the JSDoc uses an incorrect @interface tag on a type alias and the params type
isn't exported for docs; replace the @interface tag with a brief descriptive
JSDoc (optionally adding @public) above the UsePaymentMethodsReturn alias, and
add and export a new alias named UsePaymentMethodsParams that points to the
function's parameter type so Typedoc can render both parameters and return
types.

Comment on lines 46 to 76
export type UseSubscriptionReturn =
| (BaseSubscriptionReturn & {
/**
* The subscription object, or `null` if the data hasn't been loaded yet.
*/
data: null;
/**
* A boolean that indicates whether the initial data is still being fetched.
*/
isLoading: false;
/**
* A boolean that indicates whether any request is still in flight, including background updates.
*/
isFetching: false;
/**
* Any error that occurred during the data fetch, or `null` if no error occurred.
*/
error: null;
})
| (BaseSubscriptionReturn & {
data: BillingSubscriptionResource;
isLoading: true;
isFetching: true;
error: Error;
})
| (BaseSubscriptionReturn & {
data: BillingSubscriptionResource | null;
isLoading: boolean;
isFetching: boolean;
error: Error | null;
});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Fix UseSubscriptionReturn to match SWR states and actual values

Current union is internally inconsistent (e.g., data with isLoading: true and error present) and doesn’t allow undefined for initial data. Align it with SWR by simplifying the shape.

Apply this diff:

-export type UseSubscriptionReturn =
-  | (BaseSubscriptionReturn & {
-      /**
-       * The subscription object, or `null` if the data hasn't been loaded yet.
-       */
-      data: null;
-      /**
-       * A boolean that indicates whether the initial data is still being fetched.
-       */
-      isLoading: false;
-      /**
-       * A boolean that indicates whether any request is still in flight, including background updates.
-       */
-      isFetching: false;
-      /**
-       * Any error that occurred during the data fetch, or `null` if no error occurred.
-       */
-      error: null;
-    })
-  | (BaseSubscriptionReturn & {
-      data: BillingSubscriptionResource;
-      isLoading: true;
-      isFetching: true;
-      error: Error;
-    })
-  | (BaseSubscriptionReturn & {
-      data: BillingSubscriptionResource | null;
-      isLoading: boolean;
-      isFetching: boolean;
-      error: Error | null;
-    });
+export type UseSubscriptionReturn = BaseSubscriptionReturn & {
+  /**
+   * The subscription object. `undefined` before the first fetch; `null` if no subscription exists.
+   */
+  data: BillingSubscriptionResource | null | undefined;
+  /**
+   * Indicates whether the initial data is still being fetched.
+   */
+  isLoading: boolean;
+  /**
+   * Indicates whether any request is still in flight, including background updates.
+   */
+  isFetching: boolean;
+  /**
+   * Any error that occurred during the data fetch, or `undefined` if no error occurred.
+   */
+  error: Error | undefined;
+};
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export type UseSubscriptionReturn =
| (BaseSubscriptionReturn & {
/**
* The subscription object, or `null` if the data hasn't been loaded yet.
*/
data: null;
/**
* A boolean that indicates whether the initial data is still being fetched.
*/
isLoading: false;
/**
* A boolean that indicates whether any request is still in flight, including background updates.
*/
isFetching: false;
/**
* Any error that occurred during the data fetch, or `null` if no error occurred.
*/
error: null;
})
| (BaseSubscriptionReturn & {
data: BillingSubscriptionResource;
isLoading: true;
isFetching: true;
error: Error;
})
| (BaseSubscriptionReturn & {
data: BillingSubscriptionResource | null;
isLoading: boolean;
isFetching: boolean;
error: Error | null;
});
export type UseSubscriptionReturn = BaseSubscriptionReturn & {
/**
* The subscription object. `undefined` before the first fetch; `null` if no subscription exists.
*/
data: BillingSubscriptionResource | null | undefined;
/**
* Indicates whether the initial data is still being fetched.
*/
isLoading: boolean;
/**
* Indicates whether any request is still in flight, including background updates.
*/
isFetching: boolean;
/**
* Any error that occurred during the data fetch, or `undefined` if no error occurred.
*/
error: Error | undefined;
};
🤖 Prompt for AI Agents
In packages/shared/src/react/hooks/useSubscription.tsx around lines 46 to 76,
the UseSubscriptionReturn union is inconsistent with SWR states (e.g., has data
with isLoading:true and an error) and doesn't allow undefined for initial data;
simplify to three clear states: loading (data: undefined, isLoading: true,
isFetching: true, error: null), success (data: BillingSubscriptionResource,
isLoading: false, isFetching: false, error: null), and error (data:
BillingSubscriptionResource | undefined, isLoading: false, isFetching: false,
error: Error); update the union types to reflect these shapes so initial data
can be undefined and states are mutually exclusive.

Comment on lines +764 to 767
* The start date of the plan period, represented as a Unix timestamp.
*/
planPeriodStart?: number;
/**
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

🧩 Analysis chain

Clarify timestamp units and align with surrounding types

JSDoc says “Unix timestamp” but doesn’t specify seconds vs milliseconds. Nearby fields use Date. This inconsistency will confuse Typedoc consumers.

  • Specify the unit explicitly.
  • Consider using Date for consistency, or document why this one is numeric.

Would you like to align planPeriodStart to Date and update API/docs accordingly, or keep number and explicitly state the unit in the comment?


🏁 Script executed:

#!/bin/bash
rg -n 'planPeriodStart' -C3 packages/types/src/billing.ts
rg -n 'planPeriodEnd' -C3 packages/types/src/billing.ts
rg -n '\?: Date' -C3 packages/types/src/billing.ts
rg -n 'timestamp' -C2 packages/types/src/billing.ts

Length of output: 1308


Clarify timestamp unit and type for planPeriodStart

  • JSDoc “Unix timestamp” must specify seconds vs milliseconds.
  • Neighboring fields use Date; either switch this to Date or explicitly state “milliseconds since epoch” if keeping it as number.
🤖 Prompt for AI Agents
In packages/types/src/billing.ts around lines 764 to 767, the JSDoc for
planPeriodStart currently says “Unix timestamp” but doesn’t specify seconds vs
milliseconds and neighboring fields use Date; update this to be explicit and
consistent: either change the field type to Date and update the JSDoc to “The
start date of the plan period” (type Date) or, if you must keep a numeric type,
change the JSDoc to “Milliseconds since epoch (number)” and ensure the field
stays number and matches the serialization/usage elsewhere; make whichever
choice consistent with neighboring fields and update any related
imports/serializers accordingly.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
packages/shared/src/react/hooks/useReverification.ts (3)

72-75: Fix generic inference and disallow undefined fetchers

Bind the generic to the fetcher parameter and remove | undefined from the constraints. This restores proper inference and prevents invalid callers.

Apply:

-type UseReverificationResult<Fetcher extends (...args: any[]) => Promise<any> | undefined> = (
+type UseReverificationResult<Fetcher extends (...args: any[]) => Promise<any>> = (
   ...args: Parameters<Fetcher>
 ) => Promise<ExcludeClerkError<Awaited<ReturnType<Fetcher>>>>;
-export type UseReverificationParams = <Fetcher extends (...args: any[]) => Promise<any> | undefined>(
+export type UseReverificationParams = <Fetcher extends (...args: any[]) => Promise<any>>(
   /**
    * A function that returns a promise.
    */
-  fetcher: (...args: any[]) => Promise<any>,
+  fetcher: Fetcher,
   /**
    * The optional options object.
    */
   options?: UseReverificationOptions,
 ) => UseReverificationResult<Fetcher>;
-  function assertReverification<Fetcher extends (...args: any[]) => Promise<any> | undefined>(
+  function assertReverification<Fetcher extends (...args: any[]) => Promise<any>>(
     fetcher: Fetcher,
   ): (...args: Parameters<Fetcher>) => Promise<ExcludeClerkError<Awaited<ReturnType<Fetcher>>>> {

Also applies to: 79-88, 101-103


158-160: Incorrect cast target; cast the result, not the function

The as ExcludeClerkError<...> is applied to the function expression, breaking the declared return type.

Apply:

-      return result;
-    }) as ExcludeClerkError<Awaited<ReturnType<Fetcher>>>;
+      return result as ExcludeClerkError<Awaited<ReturnType<Fetcher>>>;
+    });

174-174: Docs: wrong return shape and example bug

  • The hook returns a function, not “an array”.
  • Example uses err but the catch variable is e.
- * @returns The `useReverification()` hook returns an array with the "enhanced" fetcher.
+ * @returns The `useReverification()` hook returns the enhanced fetcher function.
- *   const handleClick = async () => {
- *     try {
- *       const myData = await enhancedFetcher()
- *       //     ^ is types as `MyData`
- *     } catch (e) {
+ *   const handleClick = async () => {
+ *     try {
+ *       const myData = await enhancedFetcher()
+ *       //     ^ is typed as `MyData`
+ *     } catch (err) {
  *       // Handle error returned from the fetcher here
  *
  *       // You can also handle cancellation with the following
- *       if (isReverificationCancelledError(err)) {
+ *       if (isReverificationCancelledError(err)) {
  *         // Handle the cancellation error here
  *       }
  *     }
  *   }

Also applies to: 195-206

♻️ Duplicate comments (2)
.typedoc/custom-plugin.mjs (1)

33-33: Fix the typo in the filename.

Line 33 has a comma instead of a period before 'mdx'. This typo prevents the heading removal logic from matching the file correctly.

Apply this diff:

-  'use-reverification-params,mdx',
+  'use-reverification-params.mdx',
packages/shared/src/react/hooks/useCheckout.ts (1)

94-97: Finalize return type mismatch and JSDoc option name

API returns Promise<void> and accepts { navigate?: SetActiveNavigate }. Update type and docs to match.

     /**
-     * A function that finalizes the checkout process. Can optionally accept a `redirectUrl` to navigate the user to upon completion.
+     * Finalizes the checkout process. Optionally accepts a `navigate` callback to control post-completion navigation.
      */
-    finalize: (params?: { navigate?: SetActiveNavigate }) => void;
+    finalize: (params?: { navigate?: SetActiveNavigate }) => Promise<void>;

Based on relevant snippets (packages/types/src/clerk.ts).

🧹 Nitpick comments (3)
packages/shared/src/react/hooks/useReverification.ts (2)

40-53: Make parameters readonly and prefer optional property syntax

Improves API clarity and matches typical TS style for immutable callback containers.

-export type NeedsReverificationParameters = {
-  /**
-   * Marks the reverification process as cancelled and rejects the original request.
-   */
-  cancel: () => void;
-  /**
-   * Marks the reverification process as complete and retries the original request.
-   */
-  complete: () => void;
-  /**
-   * The verification level required for the reverification process.
-   */
-  level: SessionVerificationLevel | undefined;
-};
+export type NeedsReverificationParameters = {
+  /**
+   * Cancels the reverification process and rejects the original request.
+   */
+  readonly cancel: () => void;
+  /**
+   * Marks reverification complete and retries the original request.
+   */
+  readonly complete: () => void;
+  /**
+   * The verification level required for the reverification process.
+   */
+  readonly level?: SessionVerificationLevel;
+};

14-16: Replace placeholder JSDoc with concise summaries (improves Typedoc quality)

Empty blocks degrade docs quality.

 /**
- *
+ * Normalize fetcher results: unwrap Response to JSON and map Clerk reverification error code to a sentinel.
  */
-/**
- */
+/**
+ * Internal: creates a reverification-aware wrapper that intercepts hints and retries after completion.
+ */
 function createReverificationHandler(params: CreateReverificationHandlerParams) {
-  /**
-   *
-   */
+  /**
+   * Wrap the provided fetcher to handle reverification hints.
+   */
   function assertReverification<Fetcher extends (...args: any[]) => Promise<any> | undefined>(

Note: If you apply the earlier generic fix, also remove | undefined here.

Also applies to: 95-101

packages/shared/src/react/hooks/useCheckout.ts (1)

112-113: Export UseCheckoutParams so Typedoc can surface it

Unexported types won’t appear in generated docs, undermining the PR goal.

-type UseCheckoutParams = Parameters<typeof __experimental_CheckoutProvider>[0];
+export type UseCheckoutParams = Parameters<typeof __experimental_CheckoutProvider>[0];

If this is re-exported elsewhere already, feel free to skip; otherwise, exporting here helps Typedoc discover it.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 038c99d and 45f698d.

📒 Files selected for processing (3)
  • .typedoc/custom-plugin.mjs (3 hunks)
  • packages/shared/src/react/hooks/useCheckout.ts (2 hunks)
  • packages/shared/src/react/hooks/useReverification.ts (4 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/shared/src/react/hooks/useReverification.ts
  • packages/shared/src/react/hooks/useCheckout.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/shared/src/react/hooks/useReverification.ts
  • packages/shared/src/react/hooks/useCheckout.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/shared/src/react/hooks/useReverification.ts
  • packages/shared/src/react/hooks/useCheckout.ts
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/shared/src/react/hooks/useReverification.ts
  • packages/shared/src/react/hooks/useCheckout.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/shared/src/react/hooks/useReverification.ts
  • packages/shared/src/react/hooks/useCheckout.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/shared/src/react/hooks/useReverification.ts
  • packages/shared/src/react/hooks/useCheckout.ts
🧬 Code graph analysis (2)
packages/shared/src/react/hooks/useReverification.ts (2)
packages/types/src/sessionVerification.ts (1)
  • SessionVerificationLevel (50-50)
packages/types/src/clerk.ts (1)
  • Clerk (168-899)
packages/shared/src/react/hooks/useCheckout.ts (3)
packages/types/src/billing.ts (1)
  • BillingCheckoutResource (738-791)
packages/shared/src/error.ts (1)
  • ClerkAPIResponseError (4-4)
packages/types/src/clerk.ts (3)
  • __experimental_CheckoutCacheState (67-74)
  • __experimental_CheckoutInstance (95-102)
  • SetActiveNavigate (127-127)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Build Packages
  • GitHub Check: triage
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (3)
.typedoc/custom-plugin.mjs (2)

44-46: LGTM!

The new link replacements for checkout, reverification options, and parameters are correctly formatted and consistent with the existing anchor-link pattern.


80-80: LGTM!

The new billing resource and error type link replacements are correctly formatted and follow the established path convention.

Also applies to: 85-87

packages/shared/src/react/hooks/useCheckout.ts (1)

55-58: Doc reference fixed to BillingCheckoutResource — LGTM

This aligns wording with the actual type used.

Comment on lines 60 to 67
* A handler that is called when reverification is needed, this will opt-out of using the default UI when provided.
*
* @param cancel - A function that will cancel the reverification process.
* @param complete - A function that will retry the original request after reverification.
* @param level - The level returned with the reverification hint.
*
*/
onNeedsReverification?: (properties: NeedsReverificationParameters) => void;
};
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Fix onNeedsReverification JSDoc to document the single properties param (with nested fields)

Current tags reference non-existent params (cancel, complete, level). Use nested param docs for accuracy in Typedoc.

   /**
-   * A handler that is called when reverification is needed, this will opt-out of using the default UI when provided.
-   *
-   * @param cancel - A function that will cancel the reverification process.
-   * @param complete - A function that will retry the original request after reverification.
-   * @param level - The level returned with the reverification hint.
+   * A handler called when reverification is needed. Providing this opts out of the default UI.
+   *
+   * @param properties - Callbacks and info to control the reverification flow.
+   * @param properties.cancel - Cancels reverification and rejects the original request.
+   * @param properties.complete - Marks reverification complete and retries the original request.
+   * @param properties.level - The verification level required.
    */
   onNeedsReverification?: (properties: NeedsReverificationParameters) => void;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
* A handler that is called when reverification is needed, this will opt-out of using the default UI when provided.
*
* @param cancel - A function that will cancel the reverification process.
* @param complete - A function that will retry the original request after reverification.
* @param level - The level returned with the reverification hint.
*
*/
onNeedsReverification?: (properties: NeedsReverificationParameters) => void;
};
/**
* A handler called when reverification is needed. Providing this opts out of the default UI.
*
* @param properties - Callbacks and info to control the reverification flow.
* @param properties.cancel - Cancels reverification and rejects the original request.
* @param properties.complete - Marks reverification complete and retries the original request.
* @param properties.level - The verification level required.
*/
onNeedsReverification?: (properties: NeedsReverificationParameters) => void;
};
🤖 Prompt for AI Agents
In packages/shared/src/react/hooks/useReverification.ts around lines 60 to 67,
the JSDoc for onNeedsReverification incorrectly documents separate params
(cancel, complete, level) instead of the single properties object; update the
comment to use one @param properties describing the object and add nested @param
entries for properties.cancel, properties.complete, and properties.level (with
short descriptions of each) or otherwise describe the nested fields in the
properties description so Typedoc picks up the actual
NeedsReverificationParameters shape; remove the old individual param tags and
ensure wording matches the type names used in the code.

Copy link

pkg-pr-new bot commented Oct 15, 2025

Open in StackBlitz

@clerk/agent-toolkit

npm i https://pkg.pr.new/@clerk/agent-toolkit@6901

@clerk/astro

npm i https://pkg.pr.new/@clerk/astro@6901

@clerk/backend

npm i https://pkg.pr.new/@clerk/backend@6901

@clerk/chrome-extension

npm i https://pkg.pr.new/@clerk/chrome-extension@6901

@clerk/clerk-js

npm i https://pkg.pr.new/@clerk/clerk-js@6901

@clerk/dev-cli

npm i https://pkg.pr.new/@clerk/dev-cli@6901

@clerk/elements

npm i https://pkg.pr.new/@clerk/elements@6901

@clerk/clerk-expo

npm i https://pkg.pr.new/@clerk/clerk-expo@6901

@clerk/expo-passkeys

npm i https://pkg.pr.new/@clerk/expo-passkeys@6901

@clerk/express

npm i https://pkg.pr.new/@clerk/express@6901

@clerk/fastify

npm i https://pkg.pr.new/@clerk/fastify@6901

@clerk/localizations

npm i https://pkg.pr.new/@clerk/localizations@6901

@clerk/nextjs

npm i https://pkg.pr.new/@clerk/nextjs@6901

@clerk/nuxt

npm i https://pkg.pr.new/@clerk/nuxt@6901

@clerk/clerk-react

npm i https://pkg.pr.new/@clerk/clerk-react@6901

@clerk/react-router

npm i https://pkg.pr.new/@clerk/react-router@6901

@clerk/remix

npm i https://pkg.pr.new/@clerk/remix@6901

@clerk/shared

npm i https://pkg.pr.new/@clerk/shared@6901

@clerk/tanstack-react-start

npm i https://pkg.pr.new/@clerk/tanstack-react-start@6901

@clerk/testing

npm i https://pkg.pr.new/@clerk/testing@6901

@clerk/themes

npm i https://pkg.pr.new/@clerk/themes@6901

@clerk/types

npm i https://pkg.pr.new/@clerk/types@6901

@clerk/upgrade

npm i https://pkg.pr.new/@clerk/upgrade@6901

@clerk/vue

npm i https://pkg.pr.new/@clerk/vue@6901

commit: 6b4f930

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/shared/src/react/hooks/useReverification.ts (1)

165-176: Fix @returns doc: hook returns a function, not an array.

The current text says “returns an array,” which is misleading.

As per coding guidelines (meaningful, accurate docs for public APIs).

- * @returns The `useReverification()` hook returns an array with the "enhanced" fetcher.
+ * @returns The `useReverification()` hook returns the enhanced fetcher function.
♻️ Duplicate comments (4)
packages/shared/src/react/hooks/useReverification.ts (3)

72-75: Disallow undefined in Fetcher generic for UseReverificationResult (duplicate of prior feedback).

Fetcher must be a function; allowing undefined is incorrect and weakens typing/inference.

As per coding guidelines (avoid any/invalid types).

-type UseReverificationResult<Fetcher extends (...args: any[]) => Promise<any> | undefined> = (
+type UseReverificationResult<Fetcher extends (...args: any[]) => Promise<any>> = (
   ...args: Parameters<Fetcher>
 ) => Promise<ExcludeClerkError<Awaited<ReturnType<Fetcher>>>>;

58-67: Fix JSDoc for onNeedsReverification to document the single properties object (duplicate of prior feedback).

Current tags list non-existent params (cancel, complete, level). Document the single properties param with nested fields so TypeDoc matches the actual signature.

As per coding guidelines (public APIs must be correctly documented). Apply:

   /**
-   * A handler that is called when reverification is needed, this will opt-out of using the default UI when provided.
-   *
-   * @param cancel - A function that will cancel the reverification process.
-   * @param complete - A function that will retry the original request after reverification.
-   * @param level - The level returned with the reverification hint.
+   * A handler called when reverification is needed. Providing this opts out of the default UI.
+   *
+   * @param properties - Callbacks and info to control the reverification flow.
+   * @param properties.cancel - Cancels reverification and rejects the original request.
+   * @param properties.complete - Marks reverification complete and retries the original request.
+   * @param properties.level - The verification level required.
    */
   onNeedsReverification?: (properties: NeedsReverificationParameters) => void;

79-88: Tighten UseReverification signature to disallow undefined fetchers (duplicate of prior feedback).

Strengthen the constraint to require a function; improves inference and TypeDoc accuracy.

-type UseReverification = <Fetcher extends (...args: any[]) => Promise<any> | undefined>(
+type UseReverification = <Fetcher extends (...args: any[]) => Promise<any>>(
   /**
    * A function that returns a promise.
    */
   fetcher: Fetcher,
   /**
    * The optional options object.
    */
   options?: UseReverificationOptions,
 ) => UseReverificationResult<Fetcher>;
.typedoc/extract-returns-and-params.mjs (1)

61-110: Write -params next to the source MDX and delete -props from the same folder (duplicate of prior feedback).

Currently uses dirName (package root), causing misplaced files and wrong deletions.

Apply these diffs:

- * @param {string} dirName - The directory containing the files
  * @returns {boolean} True if a file was created
  */
-function extractParametersSection(filePath, dirName) {
+function extractParametersSection(filePath) {
   const content = fs.readFileSync(filePath, 'utf-8');
   const fileName = path.basename(filePath, '.mdx');
   const propsFileName = `${fileName}-props.mdx`;

   // Delete any existing -props file (TypeDoc-generated)
-  const propsFilePath = path.join(dirName, propsFileName);
+  const dirForFile = path.dirname(filePath);
+  const propsFilePath = path.join(dirForFile, propsFileName);
   // Write to new file
-  const newFilePath = path.join(dirName, targetFileName);
+  const newFilePath = path.join(dirForFile, targetFileName);
   fs.writeFileSync(newFilePath, paramsContent, 'utf-8');
-      // Extract Parameters sections
-      if (extractParametersSection(filePath, dir)) {
+      // Extract Parameters sections
+      if (extractParametersSection(filePath)) {
         paramsCount++;
       }

Also applies to: 170-174

🧹 Nitpick comments (4)
packages/shared/src/react/hooks/useReverification.ts (3)

101-104: Align internal generic with stricter Fetcher constraint.

Ensure assertReverification also disallows undefined.

-  function assertReverification<Fetcher extends (...args: any[]) => Promise<any> | undefined>(
+  function assertReverification<Fetcher extends (...args: any[]) => Promise<any>>(
     fetcher: Fetcher,
   ): (...args: Parameters<Fetcher>) => Promise<ExcludeClerkError<Awaited<ReturnType<Fetcher>>>> {

40-53: Prefer readonly fields and optional level for public type clarity.

Improves ergonomics and communicates immutability without runtime change.

-export type NeedsReverificationParameters = {
+export type NeedsReverificationParameters = {
   /**
    * Marks the reverification process as cancelled and rejects the original request.
    */
-  cancel: () => void;
+  readonly cancel: () => void;
   /**
    * Marks the reverification process as complete and retries the original request.
    */
-  complete: () => void;
+  readonly complete: () => void;
   /**
    * The verification level required for the reverification process.
    */
-  level: SessionVerificationLevel | undefined;
+  readonly level?: SessionVerificationLevel;
 };

14-16: Remove empty JSDoc block or add a brief description.

Empty blocks add noise and can confuse TypeDoc.

-/**
- *
- */
+/** Normalize fetcher results and map Clerk reverification errors to a hint shape. */
packages/shared/src/react/commerce.tsx (1)

4-4: Use type-only import for ReactNode to avoid pulling it into runtime.

Improves tree-shaking and aligns with “type-only imports where possible.”

As per coding guidelines.

-import React, { type PropsWithChildren, ReactNode, useCallback, useEffect, useMemo, useState } from 'react';
+import React, { useCallback, useEffect, useMemo, useState } from 'react';
+import type { PropsWithChildren, ReactNode } from 'react';
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 4cd4165 and b1888f9.

📒 Files selected for processing (3)
  • .typedoc/extract-returns-and-params.mjs (1 hunks)
  • packages/shared/src/react/commerce.tsx (4 hunks)
  • packages/shared/src/react/hooks/useReverification.ts (4 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/shared/src/react/commerce.tsx
  • packages/shared/src/react/hooks/useReverification.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/shared/src/react/commerce.tsx
  • packages/shared/src/react/hooks/useReverification.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/shared/src/react/commerce.tsx
  • packages/shared/src/react/hooks/useReverification.ts
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/shared/src/react/commerce.tsx
  • packages/shared/src/react/hooks/useReverification.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/shared/src/react/commerce.tsx
  • packages/shared/src/react/hooks/useReverification.ts
**/*.{jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{jsx,tsx}: Use error boundaries in React components
Minimize re-renders in React components

**/*.{jsx,tsx}: Always use functional components with hooks instead of class components
Follow PascalCase naming for components: UserProfile, NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...

Files:

  • packages/shared/src/react/commerce.tsx
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/shared/src/react/commerce.tsx
  • packages/shared/src/react/hooks/useReverification.ts
**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/react.mdc)

**/*.tsx: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering

Files:

  • packages/shared/src/react/commerce.tsx
🧬 Code graph analysis (2)
packages/shared/src/react/commerce.tsx (2)
packages/types/src/billing.ts (2)
  • BillingCheckoutResource (738-791)
  • ForPayerType (69-69)
packages/shared/src/react/hooks/useCheckout.ts (1)
  • useCheckout (121-198)
packages/shared/src/react/hooks/useReverification.ts (2)
packages/types/src/sessionVerification.ts (1)
  • SessionVerificationLevel (50-50)
packages/types/src/clerk.ts (1)
  • Clerk (168-899)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: Build Packages
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan

@alexisintech
Copy link
Member

@SarahSoutoul you pass parameters to a hook so let's do parameters!

Comment on lines 14 to 16
/**
*
*/
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does this need a comment, or does it need to be removed?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It doesn't need a comment, it got added automatically by my formatter. I'll remove it!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment on lines 95 to 100
/**
*/
function createReverificationHandler(params: CreateReverificationHandlerParams) {
/**
*
*/
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same here, do these need comments or does this need a cleanup?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same issue

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

* @internal
* @interface
*/
interface BaseSubscriptionReturn {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i'm curious, where did you get this addition from? o.O

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, realized this was overkill, so simplified it here: Simplify returns useSubscription.

In terms of the returns themselves, these came from the docs and the manual returns that were written there.

Comment on lines +1 to +6
---
'@clerk/shared': minor
'@clerk/types': minor
---

Ensure all hooks use typedoc for clerk docs
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think there are some changes in here that are not docs-related, that need to be mentioned in the changeset ! I'd probably check with someone from team user on their expectations for changesets 👀

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
.typedoc/custom-plugin.mjs (1)

6-6: Consider addressing the TODO as the arrays continue to grow.

Both FILES_WITHOUT_HEADINGS (now 28 entries) and LINK_REPLACEMENTS (now 51 entries) have grown significantly. The TODO on line 6 suggests moving this logic to the custom-theme to avoid post-processing.

While the current approach is functional, centralizing this logic in the theme layer could reduce maintenance overhead as the documentation surface expands.

Also applies to: 8-36, 42-93

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between b1888f9 and 912fa9c.

📒 Files selected for processing (1)
  • .typedoc/custom-plugin.mjs (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Build Packages
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (1)
.typedoc/custom-plugin.mjs (1)

21-35: LGTM! Additions are correct and typo has been resolved.

All new entries are properly formatted:

  • 15 new MDX files in FILES_WITHOUT_HEADINGS for checkout, payment, subscription, and reverification documentation
  • 7 new link mappings in LINK_REPLACEMENTS for billing resources and hook options

The typo flagged in previous reviews (use-reverification-params,mdx with comma) has been correctly fixed to use-reverification-params.mdx on line 33.

Also applies to: 46-48, 82-82, 87-89

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (1)
packages/shared/src/react/hooks/useSubscription.tsx (1)

38-56: Let data/error model SWR’s undefined state

useSWR yields undefined for both data and error before the first fetch, yet Line 40 narrows to BillingSubscriptionResource | null and Line 52 narrows to Error | null. That combination misleads consumers and mis-documents the initial state; it also contradicts the resolution from the earlier review thread. Please widen both fields to include undefined and update the JSDoc to match.

-  /**
-   * The subscription object, or `null` if the data hasn't been loaded yet.
-   */
-  data: BillingSubscriptionResource | null;
+  /**
+   * The subscription object. `undefined` before the first fetch, `null` when no subscription exists.
+   */
+  data: BillingSubscriptionResource | null | undefined;
@@
-  /**
-   * Any error that occurred during the data fetch, or `null` if no error occurred.
-   */
-  error: Error | null;
+  /**
+   * Any error that occurred during the data fetch, or `undefined` if no error occurred yet.
+   */
+  error: Error | undefined;
🧹 Nitpick comments (1)
packages/shared/src/react/hooks/useSubscription.tsx (1)

54-56: Expose the promise shape of revalidate

swr.mutate() resolves with the refreshed subscription (BillingSubscriptionResource | null | undefined). Typing Line 56 as Promise<void> hides that data from consumers and robs frictionless chaining. Please surface the actual resolved payload (and note it in the docstring).

-  /**
-   * Function to manually trigger a refresh of the subscription data.
-   */
-  revalidate: () => Promise<void>;
+  /**
+   * Function to manually trigger a refresh of the subscription data. Resolves with the latest subscription value.
+   */
+  revalidate: () => Promise<BillingSubscriptionResource | null | undefined>;
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 5c29779 and 6b4f930.

📒 Files selected for processing (1)
  • packages/shared/src/react/hooks/useSubscription.tsx (2 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/shared/src/react/hooks/useSubscription.tsx
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/shared/src/react/hooks/useSubscription.tsx
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/shared/src/react/hooks/useSubscription.tsx
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/shared/src/react/hooks/useSubscription.tsx
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/shared/src/react/hooks/useSubscription.tsx
**/*.{jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{jsx,tsx}: Use error boundaries in React components
Minimize re-renders in React components

**/*.{jsx,tsx}: Always use functional components with hooks instead of class components
Follow PascalCase naming for components: UserProfile, NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...

Files:

  • packages/shared/src/react/hooks/useSubscription.tsx
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/shared/src/react/hooks/useSubscription.tsx
**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/react.mdc)

**/*.tsx: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering

Files:

  • packages/shared/src/react/hooks/useSubscription.tsx
🧬 Code graph analysis (1)
packages/shared/src/react/hooks/useSubscription.tsx (1)
packages/types/src/billing.ts (2)
  • ForPayerType (69-69)
  • BillingSubscriptionResource (565-615)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: Build Packages
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants